(define-module (grump system)
  #:use-module (ice-9 popen)
  #:export (open-input-command
            open-output-command
            call-with-input-command
            call-with-output-command
            with-input-from-command
            with-output-to-command))

(define (open-command mode cmd)
  (let ((port (apply open-pipe* mode cmd)))
    (setvbuf port 'block)
    port))

(define (open-input-command cmd)
  (open-command OPEN_READ cmd))

(define (open-output-command cmd)
  (open-command OPEN_WRITE cmd))

(define (call-with-input-command cmd proc)
  (call-with-port (open-input-command cmd) proc))

(define (call-with-output-command cmd proc)
  (call-with-port (open-output-command cmd) proc))

(define (with-input-from-command cmd thunk)
  (call-with-input-command cmd
    (lambda (port)
      (with-input-from-port port thunk))))

(define (with-output-to-command cmd thunk)
  (call-with-output-command cmd
    (lambda (port)
      (with-output-to-port port thunk))))
